<template>
  <div class="border py-2 px-4 border-dotted">
    <a-form-item label="选择文件" class="mb-2">
      <a-button class="mr-2" @click="openSelect">选择文件</a-button>
      <a-input :model-value="''" placeholder="粘贴文件" :style="{ width: '6rem' }" class="mr-2" @paste="handlePaste" />
      <a-button @click.stop="reset">
        <template #icon>
          <Icon icon="icon-park-twotone:error" />
        </template>
      </a-button>
    </a-form-item>
    <a-form-item label="文件预览" class="mb-0">
      <span v-if="!href">None</span>
      <a-link :href="href" target="_blank" v-else>{{ href }}</a-link>
    </a-form-item>
  </div>
</template>

<script lang="ts" setup>
const file = ref<File>()
const href = useObjectUrl(file)
const reset = () => (file.value = undefined)

async function setFile(_file: File) {
  // 这里添加过滤器
  file.value = _file
}

function openSelect() {
  const upInput = document.createElement('input')
  upInput.type = 'file'
  upInput.click()
  upInput.onchange = async ({ target }) => {
    const _file = (target as HTMLInputElement)?.files?.[0]
    _file && setFile(_file)
  }
}

function handlePaste(e: ClipboardEvent) {
  const item = e.clipboardData?.items?.[0]
  if (item) {
    const { kind } = item
    if (kind === 'file') {
      const _file = item.getAsFile()
      _file && setFile(_file)
    }
  }
}

defineExpose({
  file,
  href,
})
</script>
